﻿using Common.Library.StringExt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Spider.SpiderTask
{
    public class TaskClassBase
    {
        private static Dictionary<string, TaskEntity> dic = new Dictionary<string, TaskEntity>();

        #region 创建新的线程
        public static Task TaskNew(Action action)
        {
            var temp = new Task(action);
            TaskEntity entity = new TaskEntity()
            {
                task = temp,
                StartTime = DateTime.Now,
                StartTimelong = DateTimeExt.ConvertDateTimeToInt(),
                EndTime = null
            };
            dic.Add(Guid.NewGuid().ToString(), entity);
            return temp;
        }
        #endregion

        #region 线程运行时间计算
        private static void TaskControl()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    if (dic.Count == 0)
                    {
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        List<string> tempList = new List<string>();
                        foreach (var item in dic)
                        {
                            Task tempItem = item.Value.task;
                            if (tempItem.IsCompleted)
                            {
                                //已完成
                                tempList.Add(item.Key);
                            }
                            else
                            {
                                //未完成
                                //已执行时间
                                TimeSpan span = item.Value.StartTime - DateTime.Now;
                                long time = DateTimeExt.ConvertDateTimeToInt(DateTime.Now) - item.Value.StartTimelong;
                                Console.WriteLine("线程" + item.Key + "未完成, 工执行了" + time + "毫秒");
                            }
                        }
                        for (int i = 0; i < tempList.Count; i++)
                        {
                            dic.Remove(tempList[i]);
                            Console.WriteLine("线程" + tempList[i] + "已经释放");
                        }
                        Thread.Sleep(1000);
                    }
                }
            });
        }
        #endregion


    }


    public class TaskEntity
    {
        public Task task { get; set; }
        public DateTime StartTime { get; set; }
        public long StartTimelong { get; set; }
        public DateTime? EndTime { get; set; }
    }
}
